const https = require('https');
const fs = require('fs');
const path = require('path');
 
const port = 8080;
// const host = 'localhost';
const host = '10.200.8.23';

// 私钥跟证书
const options = {
    key: fs.readFileSync("./ssl/private.key"),
    cert: fs.readFileSync("./ssl/certificate.pem"),
}

https.createServer(options, function (req, res) {
    const filePath = path.join(
      __dirname, 
      req.url === '/' ? 'index.html' : req.url
    );
   
    const extname = path.extname(filePath);
    let contentType = 'text/html';
    switch (extname) {
      case '.js':
        contentType = 'text/javascript';
        break;
      case '.css':
        contentType = 'text/css';
        break;
      case '.json':
        contentType = 'application/json';
        break;
      // ...其他文件类型
    }
   
    fs.readFile(filePath, function(error, content) {
      if (error) {
        if (error.code == 'ENOENT') {
          // 页面未找到
          fs.readFile(path.join(__dirname, '404.html'), function(error, content) {
            res.writeHead(404, { 'Content-Type': 'text/html' });
            res.end(content, 'utf-8');
          });
        } else {
          // 其他错误
          res.writeHead(500);
          res.end('Sorry, check with the server administrator for error: '+error.code+' ..\n');
        }
      } else {
        // 成功读取文件
        res.writeHead(200, { 'Content-Type': contentType });
        res.end(content, 'utf-8');
      }
    });
  }).listen(port, host, () => {
    console.log(`HTTPS 文件服务器运行在 https://${host}:${port}/`);
  });